<template>
  <div class="dialog-content">
    <el-row :gutter="40">
      <!-- 左侧表单 -->
      <el-col :span="14">
        <el-form-item label="开始日期：" prop="startDate">
          <el-date-picker
            v-model="form.startDate"
            type="date"
            placeholder="选择开始日期"
            value-format="YYYY-MM-DD"
            :disabled-date="disableBeforeToday"
          />
        </el-form-item>

        <el-form-item label="结束日期：" prop="endDate">
          <el-date-picker
            v-model="form.endDate"
            type="date"
            placeholder="选择结束日期"
            value-format="YYYY-MM-DD"
            :disabled-date="disableBeforeToday"
          />
        </el-form-item>

        <el-form-item label="随访周期：" prop="cycle">
          <el-select v-model="form.cycle" placeholder="请选择随访周期">
            <el-option
              v-for="item in cycleOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-button type="primary" @click="generateList"> 生成随访列表 </el-button>

        <div class="tip">最多只能生成10条记录</div>
        <div v-if="dates.length > 0">
          <div
            v-for="(date, index) in dates"
            :key="index"
            style="height: 40px; display: flex; align-items: center"
          >
            <span style="flex: 1">{{ date.day }}[{{ date.week }}]</span>
            <el-button type="danger" plain @click="handleDel(date, index)">删 除</el-button>
          </div>
        </div>
      </el-col>

      <!-- 右侧通知设置 -->
      <el-col :span="10">
        <el-form label-width="100px" label-position="top">
          <el-form-item label="是否通知：">
            <el-radio-group v-model="form.notice" @change="handleNoticeChange">
              <el-radio :label="true" value="1">是</el-radio>
              <el-radio :label="false" value="0">否</el-radio>
            </el-radio-group>
          </el-form-item>

<!--          <el-form-item label="选择通知方式：">
            <el-checkbox-group v-model="form.noticeType" :disabled="form.notice == '0'">
              >
              <el-checkbox label="短信" value="1" />
              <el-checkbox label="邮件" value="2" />
            </el-checkbox-group>
          </el-form-item>-->

          <el-form-item label="选择通知时间：">
            <el-select v-model="form.noticeTime" multiple :disabled="form.notice == '0'">
              <el-option
                v-for="item in notifyTimeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-date-picker
              v-if="form.noticeTime === 'custom'"
              v-model="form.customTime"
              type="datetime"
              placeholder="选择自定义时间"
              class="custom-time-picker"
            />
          </el-form-item>

          <el-form-item label="通知内容：">
            <el-input
              v-model="form.noticeContent"
              :disabled="form.notice == '0'"
              type="textarea"
              :rows="4"
              placeholder="请在此处编辑通知的内容"
            />
          </el-form-item>
          <div class="dialog-footer">
            <el-button type="primary" @click="handleSubmit">{{
              menuVal.type === 1 ? '修改预约' : '添加预约'
            }}</el-button>
          </div>
        </el-form>
      </el-col>
    </el-row>
    <!-- 预约记录 -->
    <div class="appointment-records">
      <h3>预约记录</h3>
      <el-table :data="tableData" empty-text="没有找到匹配的记录">
        <el-table-column prop="visitDate" label="随访时间" />
        <el-table-column prop="notice" label="是否通知">
          <template #default="scope">
            <span>{{ ['否', '是'][Number(scope.row.notice)] }}</span>
          </template>
        </el-table-column>
<!--        <el-table-column prop="noticeType" label="通知方式">
          <template #default="scope">
            <span v-for="(item, index) in scope.row.noticeType.split(',')" :key="index"
              >{{ ['短信', '邮件'][Number(item) - 1] }}
              <span v-if="index + 1 != scope.row.noticeType.split(',').length">|</span>
            </span>
          </template>
        </el-table-column>-->
        <el-table-column prop="noticeTime" label="通知时间">
          <template #default="scope">
            <span v-for="(item, index) in scope.row.noticeTime.split(',')" :key="index"
              >{{ ['提前一周通知', '提前三天通知', '当天通知'][Number(item) - 1] }}
              <span v-if="index + 1 != scope.row.noticeTime.split(',').length">|</span>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="noticeContent" label="通知内容" />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            {{ ['已预约', '已发送'][Number(scope.row.status) - 1] }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="text" @click="handleMenu(1, scope.row, scope.$index)">修 改</el-button>
            <el-button type="text" @click="handleMenu(2, scope.row, scope.$index)">取 消</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="plansPage.current"
          v-model:page-size="plansPage.pageSize"
          :size="size"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="plansPage.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { dictionary } from '@/api/crf/crf';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  getList,
  getDetail,
  add,
  update,
  remove,
  submitWithDays,
  getNoticeContent
} from '@/api/visitplanrecord/visitPlanRecord';
import { ref, reactive, onMounted, defineEmits,defineProps } from 'vue';
import { useRoute } from 'vue-router';
import { useStore } from 'vuex';
const store = useStore();
const route = useRoute();
const routerQuery = ref({});
routerQuery.value = route.query;
const emit = defineEmits();
const visible = ref(true);
const appointmentType = ref('单次预约');

const form = ref({
  notice: '0',
  noticeType: [],
  noticeTime: [],
  customTime: '',
  noticeContent: '',
  visitDate: new Date(),
});

let plansPage = ref({
  current: 1,
  pageSize: 10,
  total: 0,
});

const props = defineProps({
  appointmentData: {
    type: Object,
    default: {},
  }
});

let tableData = ref([]);

let cycleOptions = ref([]);

const notifyTimeOptions = ref([]);

let menuVal = ref({
  type: null,
  row: {},
  index: null,
});

/*
  type 1:修改
  type 2:取消
*/
const handleMenu = (type, row = {}, index = null) => {
  let val = JSON.parse(JSON.stringify(row));
  menuVal.value.type = type;
  menuVal.value.row = row;
  menuVal.value.index = index;
  if (type === 1) {
    val.noticeTime = val.noticeTime.split(',');
    val.noticeType = val.noticeType.split(',');
    form.value = val;
  }
  if (type === 2) {
    ElMessageBox.confirm(`确认取消${row.visitDate}随访吗`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(() => {
        return remove(row.id);
      })
      .then(() => {
        initTableData(plansPage.value);
        ElMessage.success('操作成功!');
      });
  }
};
const handleNoticeChange = () => {
  console.log('handleNoticeChange');
  form.value.noticeType = [];
  form.value.noticeTime = [];
  form.value.noticeContent = '';
  if(form.value.notice == '1'){
    getNoticeContent(getTodayDateYmd(form.value.visitDate),'2').then(res => {
      form.value.noticeContent = res.data.data;
    });
  }

};
// 表格接口
const initTableData = (page, params = {}) => {
  let values = {
    descs: 'create_time',
    ...params,
    caseUserId:props.appointmentData.id,
    trial:routerQuery.value.trialId,
  };
  getList(page.current, page.pageSize, values).then(res => {
    const DATA = res.data.data;
    plansPage.value.total = DATA.total;
    tableData.value = DATA.records;
  });
};
let dates = ref([]);
const handleSubmit = () => {
  if (dates.value.length === 0) {
    ElMessage.error('请选择正确的日期');
    return;
  }
  if (form.value.noticeType instanceof Array) {
    form.value.noticeType = form.value.noticeType.join(',');
  }
  if (form.value.noticeTime instanceof Array) {
    form.value.noticeTime = form.value.noticeTime.join(',');
  }
  form.value.caseUserId = props.appointmentData.id;
  form.value.trial = routerQuery.value.trialId;
  // delete form.value.checkbox;

  console.log(dates)

  var allDays = "";
  dates.value.forEach((item, index) => {
    allDays += item.day+",";
  });
  console.log(allDays)

  form.value.visitDays = allDays;
  submitWithDays(form.value).then(res => {
      ElMessage({
        type: 'success',
        message: '操作成功!',
      });
      //if (index + 1 === dates.value.length) {
        emit('cutChange', '单次预约');
     // }
    });
};




const handleCurrentChange  = currentPage => {
  plansPage.value.currentPage = currentPage;
  initTableData(plansPage.value);
};
const handleSizeChange = pageSize => {
  plansPage.value.pageSize = pageSize;
  initTableData(plansPage.value);
};

// import { formatDate } from 'element-plus/lib/utils/date-util';
// 生成随访记录按钮点击事件
const generateList = () => {
  if (!form.value.startDate || !form.value.endDate) return; // 如果没有选择开始或结束日期，则不进行计算

  const start = new Date(form.value.startDate);
  const end = new Date(form.value.endDate);
  let arr = [];
  const daysBetween = Math.floor((end - start) / (1000 * 60 * 60 * 24)); // 计算日期差（天数）
  let currentDate = null;
  switch (form.value.cycle) {
    case '1':
      for (let i = 0; i <= daysBetween; i++) {
        const day = new Date(start);
        day.setDate(start.getDate() + i);
        arr.push({ day: formatDate(day, 'yyyy-MM-dd'), week: getWeekday(day) });
      }
      break;

    case '2':
      if (daysBetween >= 7) {
        for (let i = 0; i <= daysBetween; i += 7) {
          const day = new Date(start);
          day.setDate(start.getDate() + i);
          arr.push({ day: formatDate(day, 'yyyy-MM-dd'), week: getWeekday(day) });
        }
      } else {
        arr.push({ day: formatDate(start, 'yyyy-MM-dd'), week: getWeekday(start) });
      }
      break;

    case '3':
      if (daysBetween >= 14) {
        for (let i = 0; i <= daysBetween; i += 14) {
          const day = new Date(start);
          day.setDate(start.getDate() + i);
          arr.push({ day: formatDate(day, 'yyyy-MM-dd'), week: getWeekday(day) });
        }
      } else {
        arr.push({ day: formatDate(start, 'yyyy-MM-dd'), week: getWeekday(start) });
      }
      break;

    case '4':
      currentDate = new Date(start);
      while (currentDate <= end) {
        arr.push({ day: formatDate(currentDate, 'yyyy-MM-dd'), week: getWeekday(currentDate) });
        currentDate.setMonth(currentDate.getMonth() + 1);
      }
      break;

    case '5':
      currentDate = new Date(start);
      while (currentDate <= end) {
        arr.push({ day: formatDate(currentDate, 'yyyy-MM-dd'), week: getWeekday(currentDate) });
        currentDate.setMonth(currentDate.getMonth() + 2);
      }
      break;

    case '6':
      currentDate = new Date(start);
      while (currentDate <= end) {
        arr.push({ day: formatDate(currentDate, 'yyyy-MM-dd'), week: getWeekday(currentDate) });
        currentDate.setFullYear(currentDate.getFullYear() + 1);
      }
      break;

    default:
      break;
  }
  if (arr.length > 10) {
    arr = arr.slice(0, 10); // 保留前 10 条数据
  }
  dates.value = arr;
};
// 删除
const handleDel = (row, index) => {
  dates.value.splice(index, 1);
};
const formatDate = (date, format) => {
  const map = {
    yyyy: date.getFullYear(),
    MM: String(date.getMonth() + 1).padStart(2, '0'),
    dd: String(date.getDate()).padStart(2, '0'),
    HH: String(date.getHours()).padStart(2, '0'),
    mm: String(date.getMinutes()).padStart(2, '0'),
    ss: String(date.getSeconds()).padStart(2, '0'),
  };

  return format.replace(/yyyy|MM|dd|HH|mm|ss/g, matched => map[matched]);
};

const getTodayDateYmd = (date) => {
  const today = new Date(date);
  const year = today.getFullYear();
  let month = today.getMonth() + 1;
  let day = today.getDate();
  month = month < 10 ? '0' + month : month; // 手动补零[1,5,6](@ref)
  day = day < 10 ? '0' + day : day;
  return `${year}年${month}月${day}日`;
};


const getWeekday = date => {
  const weekdays = ['日', '一', '二', '三', '四', '五', '六'];
  return `周${weekdays[date.getDay()]}`;
};
const initData = () => {
  notifyTimeOptions.value = [];
  cycleOptions.value = [];
  dictionary('follow_notice_time').then(res => {
    res.data.data.forEach(item => {
      notifyTimeOptions.value.push({
        label: item.dictValue,
        value: item.dictKey,
      });
    });
  });
  dictionary('period').then(res => {
    res.data.data.forEach(item => {
      cycleOptions.value.push({
        label: item.dictValue,
        value: item.dictKey,
      });
    });
  });
};
// 禁用今天之前的日期
const disableBeforeToday = date => {
  const today = new Date();
  today.setHours(0, 0, 0, 0); // 设置为今天的00:00:00，避免时间比较问题
  return date < today; // 如果日期小于今天，则禁用
};
onMounted(() => {
  initData();
  initTableData(plansPage.value);

});
</script>

<style scoped lang="scss">
.appointment-dialog {
  .calendar-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .calendar-title {
      font-size: 16px;
      color: #333;
    }
  }
  .dialog-content {
    padding: 20px;

    .calendar-section {
      .custom-calendar {
        .calendar-week-header {
          display: grid;
          grid-template-columns: repeat(7, 1fr);
          text-align: center;
          color: #666;
          margin-bottom: 10px;
        }

        .calendar-days {
          display: grid;
          grid-template-columns: repeat(7, 1fr);
          gap: 5px;

          .day-cell {
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 4px;
            cursor: pointer;

            &.selected {
              background: #409eff;
              color: white;
            }
          }
        }
      }

      .stats {
        margin-top: 20px;
        display: flex;
        gap: 30px;
        padding: 15px;
        border: 1px solid #ebeef5;
        border-radius: 4px;

        .stat-item {
          .label {
            color: #666;
            margin-right: 10px;
          }
          .value {
            color: #409eff;
            font-weight: bold;
          }
        }
      }
    }

    .appointment-records {
      margin-top: 30px;

      h3 {
        color: #333;
        margin-bottom: 15px;
      }

      .pagination {
        margin-top: 15px;
        display: flex;
        justify-content: flex-end;
        align-items: center;

        .record-info {
          color: #666;
          font-size: 12px;
        }
      }
    }

    .dialog-footer {
      margin-top: 20px;
      text-align: right;
    }
  }
}
/* 修改弹窗内容区高度 */
:deep(.el-dialog__body) {
  height: 80vh;
  overflow-y: auto; /* 添加滚动条 */
}
:deep(.el-form) {
  .el-form-item__label {
    font-weight: normal;
    color: #333;
  }
}

.custom-time-picker {
  margin-top: 10px;
  width: 100%;
}
</style>
